﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone

using BlazorAdmin.Models;
using BlazorAdmin.Interface;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using BlazorAdmin.Services.DbService;

namespace BlazorAdmin.Services
{
    internal class ExceptionService : BaMgmtDbService, IException
    {
        public ExceptionService(IPetaPoco db) : base(db) { }

        public bool Log(Error exception)
        {
            try
            {
                _ = Insert(exception);
            }
            catch { }
            return true;
        }

        public (IEnumerable<Error> Items, int ItemsCount) GetAll(string searchText, ExceptionFilter filter, int pageIndex, int pageItems, List<string> sortList)
        {
            var sql = new Sql();

            if (!string.IsNullOrEmpty(searchText))
            {
                sql.Where("ErrorPage LIKE @0 OR Message LIKE @0 OR StackTrace LIKE @0", $"%{searchText}%");
            }

            if (!string.IsNullOrEmpty(filter.Category))
            {
                sql.Where("Category = @0", filter.Category);
            }

            if (!string.IsNullOrEmpty(filter.UserId))
            {
                sql.Where("UserID LIKE @0", $"%{filter.UserId}%");
            }

            if (!string.IsNullOrEmpty(filter.ErrorPage))
            {
                sql.Where("ErrorPage LIKE @0", $"%{filter.ErrorPage}%");
            }

            sql.Where("LogTime >= @0 AND LogTime <= @1", filter.Start, filter.End);

            if (sortList.Any())
            {
                sql.OrderBy(string.Join(", ", sortList));
            }
            else
            {
                sql.OrderBy("LogTime DESC", "ErrorPage", "UserID");
            }

            using var db = Create();
            var data = db.Page<Error>(pageIndex, pageItems, sql);
            return (data.Items, Convert.ToInt32(data.TotalItems));
        }
    }
}